package com.example.springbooteasycode.zjrc.project.Koal.tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class TcpDataSender {

    // 数据封装类
    public static class CommandData {
        private byte[] data;  // 存储所有数据的字节数组
        private int position; // 当前写入位置

        public CommandData(int capacity) {
            this.data = new byte[capacity];
            this.position = 0;
        }

        // 添加无符号 short（2字节）
        public void addUnsignedShort(int value) {
            if (value < 0 || value > 65535) {
                throw new IllegalArgumentException("Value out of unsigned short range: " + value);
            }
            data[position++] = (byte) (value >> 8);
            data[position++] = (byte) value;
        }

        // 添加无符号 int（4字节）
        public void addUnsignedInt(long value) {
            if (value < 0 || value > 4294967295L) {
                throw new IllegalArgumentException("Value out of unsigned int range: " + value);
            }
            data[position++] = (byte) (value >> 24);
            data[position++] = (byte) (value >> 16);
            data[position++] = (byte) (value >> 8);
            data[position++] = (byte) value;
        }

        // 添加字节数组
        public void addBytes(byte[] bytes) {
            System.arraycopy(bytes, 0, data, position, bytes.length);
            position += bytes.length;
        }

        // 获取完整数据
        public byte[] toByteArray() {
            return java.util.Arrays.copyOf(data, position);
        }
    }

    // 发送数据到服务器
    public static void sendData(String host, int port, byte[] data) throws IOException {
        try (Socket socket = new Socket(host, port);
             OutputStream out = socket.getOutputStream()) {
            out.write(data);
            out.flush();
            System.out.println("数据发送成功，长度: " + data.length);
        }
    }

    public static void main(String[] args) {
        try {
            // 创建一个命令数据对象，假设长度为4096
            CommandData cmdData = new CommandData(4096);

            // 设置指令长度（假设为37）
            cmdData.addUnsignedShort(37);

            // 设置指令代码（0x6AB6）
            cmdData.addUnsignedShort(0x6AB6);

            // 设置交易模式（假设为1）
            cmdData.addUnsignedInt(1);

            // 添加其他数据（例如字符串）
            String payload = "Hello, Server!";
            cmdData.addBytes(payload.getBytes(StandardCharsets.UTF_8));

            // 获取完整的字节数组
            byte[] finalData = cmdData.toByteArray();
            System.out.println("发送数据: " + Arrays.toString(finalData));

            // 发送数据
            sendData("127.0.0.1", 6000, finalData);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
